define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/purchase_request/index' + location.search,
                    add_url: 'scanwork/purchase_request/add',
                    edit_url: 'scanwork/purchase_request/edit',
                    del_url: 'scanwork/purchase_request/del',
                    multi_url: 'scanwork/purchase_request/multi',
                    import_url: 'scanwork/purchase_request/import',
                    table: 'scanwork_purchase_request',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                sortOrder: 'desc',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'material.name', title: '物料名称', operate: 'LIKE'},
                        {field: 'material.code', title: '物料编码', operate: 'LIKE'},
                        {field: 'supplier.name', title: '供应商', operate: 'LIKE'},
                        {field: 'request_quantity', title: '申请数量', operate:'BETWEEN', sortable: true},
                        {field: 'priority_text', title: '优先级', formatter: function(value, row, index) {
                            var priority = String(row.priority);
                            var priorityClass = '';
                            var priorityText = '';
                            
                            switch(priority) {
                                case '1': priorityClass = 'label-default'; priorityText = '低'; break;
                                case '2': priorityClass = 'label-info'; priorityText = '中'; break;
                                case '3': priorityClass = 'label-warning'; priorityText = '高'; break;
                                case '4': priorityClass = 'label-danger'; priorityText = '紧急'; break;
                                default: priorityClass = 'label-default'; priorityText = '中'; break;
                            }
                            
                            return '<span class="label ' + priorityClass + '">' + priorityText + '</span>';
                        }},
                        {field: 'status_text', title: '状态', formatter: function(value, row, index) {
                            var status = String(row.status);
                            var statusClass = '';
                            var statusText = '';
                            
                            switch(status) {
                                case '1': statusClass = 'label-warning'; statusText = '待审核'; break;
                                case '2': statusClass = 'label-info'; statusText = '已审核'; break;
                                case '3': statusClass = 'label-success'; statusText = '已采购'; break;
                                case '4': statusClass = 'label-default'; statusText = '已取消'; break;
                                default: statusClass = 'label-default'; statusText = '未知'; break;
                            }
                            
                            return '<span class="label ' + statusClass + '">' + statusText + '</span>';
                        }},
                        {field: 'notes', title: '备注', operate: 'LIKE'},
                        {field: 'request_time', title: '申请时间', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function(value, row, index) {
                            var that = this;
                            var table = that.table;
                            var options = table ? table.bootstrapTable('getOptions') : {};
                            
                            // 使用标准的operate格式化器生成编辑删除按钮
                            var buttons = Table.api.formatter.operate.call(this, value, row, index);
                            
                            // 审核按钮（只有待审核状态才显示）
                            if (row.status == 1) {
                                buttons += ' <a class="btn btn-success btn-xs btn-approve" data-id="' + row.id + '" title="审核"><i class="fa fa-check"></i></a>';
                            }
                            
                            return buttons;
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 绑定审核按钮事件
            $(document).on('click', '.btn-approve', function() {
                var id = $(this).data('id');
                Layer.confirm('确定要审核通过这个采购申请吗？', function(index) {
                    // 使用jQuery AJAX避免FastAdmin的自动加载层
                    $.ajax({
                        url: Fast.api.fixurl('scanwork/purchase_request/approve'),
                        type: 'POST',
                        data: {ids: id},
                        dataType: 'json',
                        success: function(data) {
                            // 先关闭确认对话框
                            Layer.close(index);
                            
                            if (data.code == 1) {
                                Toastr.success(data.msg || '审核成功');
                                // 延迟刷新表格，避免加载层问题
                                setTimeout(function() {
                                    table.bootstrapTable('refresh');
                                }, 300);
                            } else {
                                Toastr.error(data.msg || '审核失败');
                            }
                        },
                        error: function(xhr, status, error) {
                            Layer.close(index);
                            Toastr.error('审核失败：' + error);
                        }
                    });
                });
            });
        },
        
        shortage: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/purchase_request/shortage' + location.search,
                    table: 'scanwork_material',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: '物料名称', operate: 'LIKE'},
                        {field: 'code', title: '物料编码', operate: 'LIKE'},
                        {field: 'stock', title: '当前库存', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '<span class="text-danger"><strong>' + value + ' ' + row.unit + '</strong></span>';
                        }},
                        {field: 'min_stock', title: '最小库存', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return value + ' ' + row.unit;
                        }},
                        {field: 'current_price', title: '参考价格', formatter: function(value, row, index) {
                            return '¥' + parseFloat(value).toFixed(2);
                        }},
                        {field: 'operate', title: __('Operate'), table: table, events: {
                            'click .btn-create-request': function(e, value, row, index) {
                                Fast.api.open('scanwork/purchase_request/createRequestDialog?material_id=' + row.id, '创建采购申请', {
                                    callback: function(data) {
                                        table.bootstrapTable('refresh');
                                    }
                                });
                            }
                        }, formatter: function(value, row, index) {
                            return '<a class="btn btn-success btn-xs btn-create-request" data-id="' + row.id + '" title="创建采购申请"><i class="fa fa-plus"></i> 申请采购</a>';
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 批量创建采购申请 - 暂时移除，改为单个创建
            // $(document).on('click', '.btn-create-request', function() {
            //     var ids = Table.api.selectedids(table);
            //     if (ids.length === 0) {
            //         Toastr.warning('请选择要创建采购申请的物料');
            //         return;
            //     }
            //     
            //     Fast.api.open('scanwork/purchase_request/createRequestDialog?material_ids=' + ids.join(','), '批量创建采购申请', {
            //         callback: function(data) {
            //             table.bootstrapTable('refresh');
            //         }
            //     });
            // });
        },
        
        // 创建采购申请对话框专用方法
        createRequestDialog: function () {
            console.log('createRequestDialog方法被调用');
            // 使用自定义的表单提交处理
            $("#create-request-form").on('submit', function (e) {
                e.preventDefault();
                console.log('表单提交事件触发');
                
                var form = $(this);
                var action = form.attr('action') || Fast.api.fixurl('scanwork/purchase_request/createRequestDialog');
                
                // 显示加载中提示
                var loading = Layer.load();
                
                // 使用jQuery AJAX提交表单
                $.post(action, form.serialize(), function (data) {
                    console.log('表单提交响应:', data);
                    // 关闭加载提示
                    Layer.close(loading);
                    
                    // 检查响应格式
                    if (data && typeof data === 'object') {
                        if (data.code == 1) {
                            // 成功处理
                            Toastr.success(data.msg || '操作成功');
                            // 如果是弹窗，关闭弹窗
                            if (parent && parent.layer) {
                                parent.layer.closeAll();
                                // 刷新父页面列表
                                if (parent.$ && parent.$.fn.bootstrapTable) {
                                    parent.$("#table").bootstrapTable('refresh');
                                }
                            } else {
                                // 如果不是弹窗，延迟跳转
                                setTimeout(function () {
                                    var url = Fast.api.fixurl('scanwork/purchase_request/index');
                                    console.log('即将跳转到:', url);
                                    location.href = url;
                                }, 1500);
                            }
                        } else {
                            // 错误处理
                            Toastr.error(data.msg || '操作失败');
                        }
                    } else {
                        // 响应格式错误
                        Toastr.error('系统响应格式错误，请稍后重试');
                    }
                }, 'json').fail(function (xhr, status, error) {
                    // 关闭加载提示
                    Layer.close(loading);
                    console.error('表单提交错误:', status, error);
                    Toastr.error('网络错误，请稍后重试');
                });
            });
            
            // 为重置按钮添加事件
            $("button[type='reset']").on('click', function () {
                console.log('重置按钮被点击');
                Form.api.clearform($("#create-request-form"));
            });
        },

        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            
            updateSubmitButton: function() {
                var hasSelected = $('.material-checkbox:checked').length > 0;
                var hasSupplier = $('#c-supplier_id').val() !== '';
                $('button[type="submit"]').toggleClass('disabled', !(hasSelected && hasSupplier));
            }
        }
    };
    return Controller;
});
